import React, { useState, useEffect, useRef } from 'react';
import * as echarts from 'echarts';
import './Stats.css';

export const Stats: React.FC = () => {
  const [herbs, setHerbs] = useState<any[]>([]);
  const [relations, setRelations] = useState<any[]>([]);
  const [isLoading, setIsLoading] = useState<boolean>(true);
  
  // 图表引用
  const categoryPieRef = useRef<HTMLDivElement>(null);
  const natureBarRef = useRef<HTMLDivElement>(null);
  const functionDistRef = useRef<HTMLDivElement>(null);
  const relationshipNetworkRef = useRef<HTMLDivElement>(null);
  
  // 加载数据
  useEffect(() => {
    const loadData = async () => {
      try {
        setIsLoading(true);
        
        // 加载药材数据
        const herbsResponse = await fetch('/src/data/herbs.json');
        const herbsData = await herbsResponse.json();
        const herbsList = Object.values(herbsData);
        setHerbs(herbsList);
        
        // 加载关系数据
        const relationsResponse = await fetch('/src/data/relations.csv');
        const relationsText = await relationsResponse.text();
        const relationsList = relationsText.split('\n')
          .slice(1) // 跳过标题行
          .filter(line => line.trim() !== '')
          .map(line => {
            const [source, target, type, strength] = line.split(',');
            return { source, target, type, strength: parseFloat(strength) };
          });
        setRelations(relationsList);
        
        setIsLoading(false);
      } catch (error) {
        console.error('Failed to load data:', error);
        setIsLoading(false);
      }
    };

    loadData();
  }, []);
  
  // 初始化图表
  useEffect(() => {
    if (isLoading || !herbs.length) return;
    
    // 准备数据
    const categoryCount: Record<string, number> = {};
    const natureCount: Record<string, number> = {};
    const flavorCount: Record<string, number> = {};
    const functionCount: Record<string, number> = {};
    
    herbs.forEach(herb => {
      // 统计分类
      categoryCount[herb.category] = (categoryCount[herb.category] || 0) + 1;
      
      // 统计药性
      natureCount[herb.properties.性] = (natureCount[herb.properties.性] || 0) + 1;
      
      // 统计药味
      herb.properties.味.forEach((flavor: string) => {
        flavorCount[flavor] = (flavorCount[flavor] || 0) + 1;
      });
      
      // 统计功效
      herb.functions.forEach((func: string) => {
        functionCount[func] = (functionCount[func] || 0) + 1;
      });
    });
    
    // 分类饼图
    if (categoryPieRef.current) {
      const categoryChart = echarts.init(categoryPieRef.current);
      categoryChart.setOption({
        title: {
          text: '药材分类统计',
          left: 'center',
          textStyle: {
            color: '#333',
            fontFamily: 'SimSun, STSong, serif'
          }
        },
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b}: {c} ({d}%)'
        },
        legend: {
          orient: 'vertical',
          left: 'left',
          top: 'middle'
        },
        series: [
          {
            name: '药材分类',
            type: 'pie',
            radius: '55%',
            center: ['60%', '50%'],
            data: Object.entries(categoryCount).map(([name, value]) => ({ name, value })),
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
              }
            },
            label: {
              formatter: '{b}: {c} ({d}%)'
            }
          }
        ]
      });
      
      // 响应式调整
      window.addEventListener('resize', () => {
        categoryChart.resize();
      });
    }
    
    // 药性柱状图
    if (natureBarRef.current) {
      const natureChart = echarts.init(natureBarRef.current);
      
      const natureData = Object.entries(natureCount).map(([name, value]) => ({ name, value }));
      const flavorData = Object.entries(flavorCount).map(([name, value]) => ({ name, value }));
      
      natureChart.setOption({
        title: {
          text: '药性与药味分布',
          left: 'center',
          textStyle: {
            color: '#333',
            fontFamily: 'SimSun, STSong, serif'
          }
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        legend: {
          data: ['药性', '药味'],
          top: 30
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: [
          {
            type: 'value'
          }
        ],
        yAxis: [
          {
            type: 'category',
            data: [...new Set([...natureData.map(d => d.name), ...flavorData.map(d => d.name)])]
          }
        ],
        series: [
          {
            name: '药性',
            type: 'bar',
            stack: 'total',
            label: {
              show: true
            },
            emphasis: {
              focus: 'series'
            },
            data: natureData.map(d => d.value)
          },
          {
            name: '药味',
            type: 'bar',
            stack: 'total',
            label: {
              show: true
            },
            emphasis: {
              focus: 'series'
            },
            data: flavorData.map(d => d.value)
          }
        ]
      });
      
      // 响应式调整
      window.addEventListener('resize', () => {
        natureChart.resize();
      });
    }
    
    // 功效分布图
    if (functionDistRef.current) {
      const functionChart = echarts.init(functionDistRef.current);
      
      // 只取前10个功效，防止图表过于复杂
      const topFunctions = Object.entries(functionCount)
        .sort((a, b) => b[1] - a[1])
        .slice(0, 12)
        .map(([name, value]) => ({ name, value }));
      
      functionChart.setOption({
        title: {
          text: '药材功效统计',
          left: 'center',
          textStyle: {
            color: '#333',
            fontFamily: 'SimSun, STSong, serif'
          }
        },
        tooltip: {
          trigger: 'item'
        },
        toolbox: {
          feature: {
            saveAsImage: {}
          }
        },
        series: [
          {
            name: '功效数量',
            type: 'treemap',
            data: topFunctions,
            label: {
              show: true,
              formatter: '{b}: {c}'
            },
            breadcrumb: {
              show: false
            }
          }
        ]
      });
      
      // 响应式调整
      window.addEventListener('resize', () => {
        functionChart.resize();
      });
    }
    
    // 关系网络图
    if (relationshipNetworkRef.current && relations.length) {
      const networkChart = echarts.init(relationshipNetworkRef.current);
      
      // 准备节点和边数据
      const nodes = herbs.map(herb => ({
        id: herb.id,
        name: herb.name,
        symbolSize: 20,
        category: herb.category
      }));
      
      const edges = relations.map(rel => ({
        source: rel.source,
        target: rel.target,
        value: rel.type,
        lineStyle: {
          width: rel.strength * 5,
          color: getRelationColor(rel.type)
        }
      }));
      
      // 获取分类列表作为图例
      const categories = Array.from(new Set(herbs.map(herb => herb.category))).map(category => ({
        name: category
      }));
      
      networkChart.setOption({
        title: {
          text: '药材关系网络',
          left: 'center',
          textStyle: {
            color: '#333',
            fontFamily: 'SimSun, STSong, serif'
          }
        },
        tooltip: {
          formatter: function(params: any) {
            if (params.dataType === 'node') {
              return `${params.data.name} (${params.data.category})`;
            } else {
              return `${params.data.source} → ${params.data.target}<br/>${params.data.value}`;
            }
          }
        },
        legend: {
          data: categories.map(c => c.name),
          orient: 'vertical',
          left: 'left',
          top: 50
        },
        series: [
          {
            type: 'graph',
            layout: 'force',
            data: nodes,
            links: edges,
            categories: categories,
            roam: true,
            label: {
              show: true,
              position: 'right',
              formatter: '{b}'
            },
            force: {
              repulsion: 100,
              edgeLength: [50, 100]
            },
            emphasis: {
              focus: 'adjacency',
              lineStyle: {
                width: 10
              }
            }
          }
        ]
      });
      
      // 响应式调整
      window.addEventListener('resize', () => {
        networkChart.resize();
      });
    }
    
    // 清理函数
    return () => {
      if (categoryPieRef.current) {
        echarts.getInstanceByDom(categoryPieRef.current)?.dispose();
      }
      if (natureBarRef.current) {
        echarts.getInstanceByDom(natureBarRef.current)?.dispose();
      }
      if (functionDistRef.current) {
        echarts.getInstanceByDom(functionDistRef.current)?.dispose();
      }
      if (relationshipNetworkRef.current) {
        echarts.getInstanceByDom(relationshipNetworkRef.current)?.dispose();
      }
    };
  }, [herbs, relations, isLoading]);
  
  // 辅助函数：根据关系类型返回颜色
  const getRelationColor = (type: string) => {
    const colorMap: Record<string, string> = {
      '相须': '#4CAF50',
      '相使': '#2196F3',
      '相畏': '#FFC107',
      '相恶': '#F44336',
      '相反': '#9C27B0',
      '相杀': '#FF9800',
      '相陈': '#607D8B'
    };
    
    return colorMap[type] || '#999';
  };
  
  if (isLoading) {
    return (
      <div className="loading">
        <div className="loading-spinner"></div>
        <p>正在加载统计数据...</p>
      </div>
    );
  }
  
  return (
    <div className="stats-container">
      <header className="app-header">
        <h1>本草纲目数据统计分析</h1>
      </header>
      
      <main className="stats-content">
        <div className="stats-row">
          <div className="stats-card card">
            <div 
              ref={categoryPieRef} 
              className="chart-container"
            ></div>
          </div>
          
          <div className="stats-card card">
            <div 
              ref={natureBarRef} 
              className="chart-container"
            ></div>
          </div>
        </div>
        
        <div className="stats-row">
          <div className="stats-card card">
            <div 
              ref={functionDistRef} 
              className="chart-container"
            ></div>
          </div>
          
          <div className="stats-card card">
            <div 
              ref={relationshipNetworkRef} 
              className="chart-container large-chart"
            ></div>
          </div>
        </div>
      </main>
    </div>
  );
}; 